All files / src/components/admin EditContentDialog.tsx

0% Statements 0/120
0% Branches 0/117
0% Functions 0/23
0% Lines 0/117

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
'use client';
 
import { useCallback, useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { AlertCircle, Trash2 } from 'lucide-react';
import { contentService } from '@/services';
import { Content } from '@/types';
import { useTranslation } from 'react-i18next';
import useLoadNamespace from '@/hooks/useLoadNamespace';
import { extractErrorMessage } from '@/lib/error-message';
import i18nInstance from '@/lib/i18n';
 
// Validation schema - allow URLs or local media paths
const editContentSchema = z.object({
  title: z.string().min(1, i18nInstance.t('manualSeries.titleRequired')),
  description: z.string().optional(),
  year: z.number().min(1900).max(new Date().getFullYear() + 5).optional(),
  poster_url: z.string().url(i18nInstance.t('errors.invalidData')).optional().or(z.literal('')),
  backdrop_url: z.string().url(i18nInstance.t('errors.invalidData')).optional().or(z.literal('')),
  video_url: z.string().min(1, i18nInstance.t('seriesManagement.videoUrlRequired')).refine(
    (val) => val.startsWith('http://') || val.startsWith('https://') || val.startsWith('/media/') || val.startsWith('/'),
    i18nInstance.t('errors.invalidData')
  ),
  active: z.boolean()});
 
type EditContentData = z.infer<typeof editContentSchema>;
 
interface EditContentDialogProps {
  isOpen: boolean;
  onClose: () => void;
  content: Content;
  onSuccess: () => void;
}
 
export default function EditContentDialog({
  isOpen,
  onClose,
  content,
  onSuccess}: EditContentDialogProps) {
  const form = useForm<EditContentData>({
    resolver: zodResolver(editContentSchema),
    defaultValues: {
      title: '',
      description: '',
      year: undefined,
      poster_url: '',
      backdrop_url: '',
      video_url: '',
      active: true}});
 
  useLoadNamespace('admin/editContent');
  const { t } = useTranslation(['admin/editContent', 'admin', 'translation']);
 
  // Update content mutation
  const updateContentMutation = useMutation({
    mutationFn: async (data: EditContentData) => {
      const result = await contentService.updateContent(content.id, data);
      if (result.success) {
        return result.data;
      }
      throw new Error(extractErrorMessage(result.error, t('common.serverError')));
    },
    onSuccess: () => {
      onSuccess();
    }});
 
  // Track loaded subtitles for chips
  const [subtitleTracks, setSubtitleTracks] = useState<Array<{ id: number; language: string; label?: string; url?: string; }>>([]);
  const [subtitleLanguage, setSubtitleLanguage] = useState('en');
  const [subtitleFile, setSubtitleFile] = useState<File | null>(null);
  const [deletingSubtitleId, setDeletingSubtitleId] = useState<number | null>(null);
  const subtitleFileInputRef = useRef<HTMLInputElement | null>(null);
  const canUploadManualSubtitles = ['vod', 'series', 'anime', 'kids'].includes(
    String(content.content_type || '').toLowerCase()
  );
 
  const loadContentForEdit = useCallback(async () => {
    try {
      const result = await contentService.getContentForEdit(content.id);
      if (result.success) {
        const editableContent: any = result.data;
        form.setValue('title', editableContent.title);
        form.setValue('description', editableContent.description || '');
        form.setValue('year', editableContent.year || undefined);
        form.setValue('poster_url', editableContent.poster_url || editableContent.image_url || '');
        form.setValue('backdrop_url', editableContent.backdrop_url || '');
        // Backend returns stream_url, map to video_url for form
        form.setValue('video_url', editableContent.stream_url || editableContent.video_url || '');
        form.setValue('active', editableContent.active);
        // Load subtitles array if provided by backend
        if (Array.isArray(editableContent.subtitles) && editableContent.subtitles.length > 0) {
          setSubtitleTracks(editableContent.subtitles.map((s: any) => ({
            id: Number(s.id),
            language: String(s.language || '').toUpperCase(),
            label: s.label,
            url: s.url})));
        } else {
          // Fallback: fetch stream info to discover subtitles list if edit payload doesn't include them
          try {
            const streamRes = await contentService.getStreamUrl(content.id);
            const subs: any[] | undefined = (streamRes.success && streamRes.data && Array.isArray((streamRes.data as any).subtitles))
              ? (streamRes.data as any).subtitles
              : undefined;
 
            if (subs && subs.length > 0) {
              setSubtitleTracks(subs.map((s: any) => ({
                id: Number(s.id),
                language: String(s.language || '').toUpperCase(),
                label: s.label,
                url: s.url})));
            } else {
              setSubtitleTracks([]);
            }
          } catch {
            setSubtitleTracks([]);
          }
        }
      } else {
        console.error('Failed to load content for editing:', result.error);
        // Fallback to original content data
        form.setValue('title', content.title);
        form.setValue('description', content.description || '');
        form.setValue('year', content.year || undefined);
        form.setValue('poster_url', content.poster_url || content.image_url || '');
        form.setValue('backdrop_url', content.backdrop_url || '');
        form.setValue('video_url', (content as any).stream_url || content.video_url || '');
        form.setValue('active', content.active);
        setSubtitleTracks([]);
      }
    } catch (error) {
      console.error('Error loading content for editing:', error);
      // Fallback to original content data
      form.setValue('title', content.title);
      form.setValue('description', content.description || '');
      form.setValue('year', content.year || undefined);
      form.setValue('poster_url', content.poster_url || content.image_url || '');
      form.setValue('backdrop_url', content.backdrop_url || '');
      form.setValue('video_url', (content as any).stream_url || content.video_url || '');
      form.setValue('active', content.active);
      setSubtitleTracks([]);
    }
  }, [content, form]);
 
  const uploadSubtitleMutation = useMutation({
    mutationFn: async () => {
      if (!subtitleFile) {
        throw new Error(t('editContent.validation.subtitleFileRequired'));
      }
      const result = await contentService.uploadContentSubtitle(
        content.id,
        subtitleFile,
        subtitleLanguage
      );
      if (result.success) {
        return result.data;
      }
      throw new Error(extractErrorMessage(result.error, t('common.serverError')));
    },
    onSuccess: async () => {
      await loadContentForEdit();
      setSubtitleFile(null);
      if (subtitleFileInputRef.current) {
        subtitleFileInputRef.current.value = '';
      }
    }});
 
  const deleteSubtitleMutation = useMutation({
    mutationFn: async (subtitleId: number) => {
      const result = await contentService.deleteContentSubtitle(content.id, subtitleId);
      if (result.success) {
        return result.data;
      }
      throw new Error(extractErrorMessage(result.error, t('common.serverError')));
    },
    onMutate: (subtitleId) => {
      setDeletingSubtitleId(subtitleId);
    },
    onSuccess: async () => {
      await loadContentForEdit();
    },
    onSettled: () => {
      setDeletingSubtitleId(null);
    }});
 
  // Load content data into form when dialog opens
  useEffect(() => {
    if (isOpen && content) {
      loadContentForEdit();
    }
  }, [content, isOpen, loadContentForEdit]);
 
  const handleSubmit = (data: EditContentData) => {
    updateContentMutation.mutate(data);
  };
 
  const getContentTypeLabel = () => {
    switch (content.content_type) {
      case 'vod': return t('contentType.movie');
      case 'tv': return t('contentTypeExtended.tvChannel');
      case 'series': return t('contentTypeExtended.tvSeries');
      case 'events': return t('contentTypeExtended.event');
      case 'kids': return t('contentType.kids');
      case 'anime': return t('contentTypeExtended.anime');
      default: return t('contentTypeExtended.content');
    }
  };
 
  return (
    <Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose(); }}>
      <DialogContent className="!max-w-[65vw] !w-[65vw] max-h-[75vh] overflow-y-auto sm:!max-w-[65vw] md:!max-w-[65vw] lg:!max-w-[65vw]" style={{ width: '65vw', maxWidth: '65vw' }}>
        <DialogHeader>
          <DialogTitle>{t('common.edit')} {getContentTypeLabel()}</DialogTitle>
          <DialogDescription>
            {t('createContent.description', { type: getContentTypeLabel() })}
          </DialogDescription>
        </DialogHeader>
 
        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="edit-title">{t('createContent.labels.title')} *</Label>
              <Input
                id="edit-title"
                {...form.register('title')}
                placeholder={t('createContent.form.titlePlaceholder')}
              />
              {form.formState.errors.title && (
                <p className="text-sm text-red-600 mt-1">
                  {form.formState.errors.title.message}
                </p>
              )}
            </div>
            <div>
              <Label htmlFor="edit-year">{t('editContent.labels.year')}</Label>
              <Input
                id="edit-year"
                type="number"
                min="1900"
                max={new Date().getFullYear() + 5}
                {...form.register('year', { valueAsNumber: true })}
                placeholder={t('createContent.form.yearPlaceholder')}
              />
              {form.formState.errors.year && (
                <p className="text-sm text-red-600 mt-1">
                  {form.formState.errors.year.message}
                </p>
              )}
            </div>
          </div>
 
          <div>
            <Label htmlFor="edit-description">{t('editContent.labels.description')}</Label>
            <Textarea
              id="edit-description"
              {...form.register('description')}
              placeholder={t('createContent.form.descriptionPlaceholder')}
              rows={3}
            />
          </div>
 
          <div>
            <Label htmlFor="edit-video-url">{t('editContent.labels.videoUrl')} *</Label>
            <Input
              id="edit-video-url"
              {...form.register('video_url')}
              placeholder={t('createContent.form.videoUrlPlaceholder')}
            />
            {form.formState.errors.video_url && (
              <p className="text-sm text-red-600 mt-1">
                {form.formState.errors.video_url.message}
              </p>
            )}
          </div>
 
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="edit-poster-url">{t('createContent.labels.posterUrl')}</Label>
              <Input
                id="edit-poster-url"
                {...form.register('poster_url')}
                placeholder={t('createContent.form.posterUrlPlaceholder')}
              />
              {form.formState.errors.poster_url && (
                <p className="text-sm text-red-600 mt-1">
                  {form.formState.errors.poster_url.message}
                </p>
              )}
            </div>
            <div>
              <Label htmlFor="edit-backdrop-url">{t('createContent.labels.backdropUrl')}</Label>
              <Input
                id="edit-backdrop-url"
                {...form.register('backdrop_url')}
                placeholder={t('createContent.form.backdropUrlPlaceholder')}
              />
              {form.formState.errors.backdrop_url && (
                <p className="text-sm text-red-600 mt-1">
                  {form.formState.errors.backdrop_url.message}
                </p>
              )}
            </div>
          </div>
 
          {/* Subtitles chips */}
          <div className="mt-3">
            <Label>{t('editContent.labels.subtitles')}</Label>
            {subtitleTracks.length === 0 ? (
              <p className="text-xs text-muted-foreground mt-1">{t('editContent.noSubtitles')}</p>
            ) : (
              <div className="flex flex-wrap gap-2 mt-1">
                {subtitleTracks.map((s) => (
                  <div
                    key={s.id}
                    className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border bg-white"
                    title={s.label || s.language}
                  >
                    <a
                      href={s.url || '#'}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex items-center gap-1 hover:text-primary transition"
                    >
                      <span className="font-mono">{s.language}</span>
                      {s.label ? <span className="text-muted-foreground">({s.label})</span> : null}
                    </a>
                    <button
                      type="button"
                      className="text-red-600 hover:text-red-700 disabled:opacity-50"
                      onClick={() => {
                        const confirmed = window.confirm(`${t('common.delete')} ${t('editContent.labels.subtitles').toLowerCase()} ${s.language}?`);
                        if (confirmed) {
                          deleteSubtitleMutation.mutate(s.id);
                        }
                      }}
                      disabled={deleteSubtitleMutation.isPending && deletingSubtitleId === s.id}
                      title={`${t('common.delete')} ${t('editContent.labels.subtitles').toLowerCase()}`}
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                ))}
              </div>
            )}
 
            {canUploadManualSubtitles ? (
              <div className="mt-3 rounded-md border p-3 bg-muted/20">
                <div className="grid grid-cols-1 md:grid-cols-[110px_1fr_auto] gap-2 items-end">
                  <div>
                    <Label htmlFor="subtitle-language">{t('common.language')}</Label>
                    <Input
                      id="subtitle-language"
                      value={subtitleLanguage}
                      onChange={(e) => setSubtitleLanguage(e.target.value.trim().toLowerCase())}
                      placeholder={t('editContent.subtitleLanguagePlaceholder')}
                      maxLength={16}
                    />
                  </div>
                  <div>
                    <Label htmlFor="subtitle-file">{t('editContent.labels.subtitles')} (.srt/.vtt)</Label>
                    <Input
                      id="subtitle-file"
                      ref={subtitleFileInputRef}
                      type="file"
                      accept=".srt,.vtt,text/vtt,application/x-subrip"
                      onChange={(e) => setSubtitleFile(e.target.files?.[0] ?? null)}
                    />
                  </div>
                  <Button
                    type="button"
                    onClick={() => uploadSubtitleMutation.mutate()}
                    disabled={
                      uploadSubtitleMutation.isPending ||
                      !subtitleFile ||
                      !subtitleLanguage.trim()
                    }
                  >
                    {uploadSubtitleMutation.isPending
                      ? t('common.uploading')
                      : `${t('common.upload')} ${t('editContent.labels.subtitles').toLowerCase()}`}
                  </Button>
                </div>
                {uploadSubtitleMutation.error ? (
                  <p className="text-sm text-red-600 mt-2">
                    {(uploadSubtitleMutation.error as Error).message}
                  </p>
                ) : null}
                {deleteSubtitleMutation.error ? (
                  <p className="text-sm text-red-600 mt-2">
                    {(deleteSubtitleMutation.error as Error).message}
                  </p>
                ) : null}
              </div>
            ) : null}
          </div>
 
          <div className="flex items-center space-x-2">
            <Switch
              id="edit-active"
              checked={form.watch('active')}
              onCheckedChange={(checked) => form.setValue('active', checked)}
            />
            <Label htmlFor="edit-active">{t('common.active')}</Label>
          </div>
 
          {content.tmdb_id && (
            <Alert>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                {t('admin.content.tmdb.confirm', { category: getContentTypeLabel() })} ID: {content.tmdb_id}. {t('admin.content.tmdb.warning')}
              </AlertDescription>
            </Alert>
          )}
 
          {updateContentMutation.error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                {updateContentMutation.error.message}
              </AlertDescription>
            </Alert>
          )}
 
          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              {t('common.cancel')}
            </Button>
            <Button
              type="submit"
              disabled={updateContentMutation.isPending}
            >
              {updateContentMutation.isPending ? t('common.saving') : t('common.save')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}